package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.dto.DeviceDataPageQueryDto;
import com.zzyl.nursing.domain.pojo.Device;
import com.zzyl.nursing.domain.pojo.DeviceData;
import com.zzyl.nursing.job.IotMsgHeader;
import com.zzyl.nursing.job.IotMsgNotifyData;
import com.zzyl.nursing.job.IotMsgService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-05-30
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    
    @Autowired
    IDeviceService deviceService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void batchSave(IotMsgNotifyData notifyData) {
        IotMsgHeader header = notifyData.getHeader();
        String deviceId = header.getDeviceId();
        Device device = deviceService.lambdaQuery()
                .eq(Device::getIotId, deviceId)
                .one();
        // 2，数据判断
        if (ObjectUtils.isNull(device)){
            return;
        }
        List<IotMsgService> services = notifyData.getBody().getServices();
        if (CollectionUtil.isEmpty(services)) {
            return;
        }
        // 3，对Properties数据进行循环构建DeviceData对象，然后做批量保存
        services.forEach(service-> {
            // 解析时间->将字符串时间转换为LocalDateTime类型
            LocalDateTime localDateTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = localDateTime.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            // 构建DeviceData对象
            Map<String, Object> properties = service.getProperties();
            ArrayList<DeviceData> deviceDataList = new ArrayList<>(properties.size());
            properties.forEach((k,v)->{
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class, CopyOptions.create().setIgnoreProperties("id"));
                deviceData.setAccessLocation(device.getBindingLocation());
                deviceData.setFunctionId(k);
                deviceData.setDataValue(v.toString());
                deviceData.setAlarmTime(eventTime);
                deviceDataList.add(deviceData);
            });
            saveBatch(deviceDataList);
            // 将罪行的数据存储到redis数据库库中
            stringRedisTemplate.opsForHash().put(Constants.IOT_LAST_DEVICE_DATA_LIST,deviceId, JSONUtil.toJsonStr(deviceDataList));
        });
    }

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceDataPageQueryDto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageQueryDto deviceDataPageQueryDto)
    {
        String functionId = deviceDataPageQueryDto.getFunctionId();
        String deviceName = deviceDataPageQueryDto.getDeviceName();
        if (StrUtil.isBlank(functionId)||StrUtil.isBlank(deviceName)) {
            throw new ServiceException("功能id或设备名称不能为空");
        }
        LocalDateTime startTime = deviceDataPageQueryDto.getStartTime();
        LocalDateTime endTime = deviceDataPageQueryDto.getEndTime();
        if (ObjectUtils.isNull(startTime)||ObjectUtils.isNull(endTime)) {
            throw new ServiceException("开始时间或结束时间不能为空");
        }
        Page<DeviceData> page = this.lambdaQuery()
                .eq(DeviceData::getFunctionId, functionId)
                .eq(DeviceData::getDeviceName, deviceName)
                .between(DeviceData::getAlarmTime, startTime, endTime)
                .page(Page.of(deviceDataPageQueryDto.getPageNum(), deviceDataPageQueryDto.getPageSize()));
        return TableDataInfo.getDataTable(page.getRecords(),page.getTotal());
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }
}
